package com.jwgf.canstate;

import com.jwgf.can.CanMessage;
import com.jwgf.comlibrary.CANManager;
import com.jwgf.protocolstack.ProtocolStack;
import com.jwgf.protocolstack.ProtocolStackState;
import com.jwgf.smarowindingmachine_unity.logic.SmaroWindingMachineCanReadSucceedListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.HashSet;

public class SmaroCanState implements ProtocolStackState {
    private byte[] data = null;
    private ProtocolStack stack;
    private HashSet<Integer> filterSet = new HashSet<>(50);

    public SmaroCanState(ProtocolStack stack) {
        this.stack = stack;
        filterSet.add(0xE0);
        filterSet.add(0x10);
        filterSet.add(0x15);
        filterSet.add(0x16);
        filterSet.add(0x20);
        filterSet.add(0x21);
        filterSet.add(0x22);
        filterSet.add(0x23);
        filterSet.add(0x24);
        filterSet.add(0x25);
        filterSet.add(0x26);
        filterSet.add(0x27);
        filterSet.add(0x28);
        filterSet.add(0x29);
        filterSet.add(0x2A);
        filterSet.add(0x2C);
        filterSet.add(0x2D);
        filterSet.add(0x30);
        filterSet.add(0x31);
        filterSet.add(0x32);
        filterSet.add(0x33);
        filterSet.add(0x39);
        filterSet.add(0x75);
        EventBus.getDefault().register(this);

    }

    @Override
    public void handleSend(ProtocolStack stack) {
        int canId = (data[0] << 8) | (data[1] & 0xff);
        byte[] sendData = new byte[8];
        System.arraycopy(data, 2, sendData, 0, sendData.length);
        CANManager.getInstance().write1(canId, sendData);
    }

    @Override
    public void handleRecv(ProtocolStack stack, byte[] recv) {
        data = new byte[]{0x00, recv[3], (byte) 0xE0, 0x01, recv[2], recv[3], 0, 0, 0, 0};
        stack.send();
        stack.notifyReadSucceedListeners(recv);
    }

    @Subscribe
    public void receive(CanMessage msg) {
        byte[] data = msg.getData();
        int canId = data[1] & 0xff;
        int canfilter = data[2] & 0xff;
        if (canId == 1) {
            if (!filterSet.contains(canfilter)) {
                handleRecv(stack, data);
                EventBus.getDefault().cancelEventDelivery(msg);
            }
        } else if (canId == 0x55 && canfilter == 0xEE) {
            int aliveId = (data[4] & 0xff) - 1;
            SmaroWindingMachineCanReadSucceedListener.getInstance().setSpindleToken(aliveId, true);
        }

    }
}
